<!-- 文章管理 - 弹框 -->
<template>
    <!-- :before-close="handleClose" -->
    <el-drawer
    custom-class="elDrawer"
    v-model="drawer"
    :title="typeTitle + '文章'"
    direction="btt"
    size="75%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="handleClose">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
            <el-row>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="文章标题" prop="articleTitle">
                        <el-input v-model="form.articleTitle" :readonly="billState" placeholder="请输入文章标题"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="文章封面" prop="articleCover">
                        <el-input v-model="form.articleCover" :readonly="billState" placeholder="请输入文章封面链接"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="文章作者" prop="articleAuthor">
                        <el-input v-model="form.articleAuthor" :readonly="billState" placeholder="请输入文章作者"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="转载地址" prop="reprint">
                        <el-input v-model="form.reprint" :readonly="billState" placeholder="请输入转载地址"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="文章标签" prop="tags">
                        <el-select multiple :disabled="billState" v-model="form.tags" placeholder="请选择文章标签">
                            <el-option 
                            v-for="item in tagList" 
                            :key="item.id" 
                            :label="item.tagName" 
                            :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :sm="12" :md="6" :xl="4">
                    <el-form-item label="文章类别" prop="sortId">
                        <el-select v-model="form.sortId" :disabled="billState" @change="sortChange" placeholder="请选择文章类别">
                            <el-option 
                            v-for="item in articleTypeList" 
                            :key="item.id" 
                            :label="item.sortName"
                            :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :sm="6" :md="3" :xl="2">
                    <el-form-item label="是否置顶" prop="isTop">
                        <el-switch v-model="form.isTop" :disabled="billState"/>
                    </el-form-item>
                </el-col>
                <el-col :sm="6" :md="3" :xl="2">
                    <el-form-item label="是否火热" prop="isHot">
                        <el-switch v-model="form.isHot" :disabled="billState"/>
                    </el-form-item>
                </el-col>
                <el-col :sm="6" :md="3" :xl="2">
                    <el-form-item label="是否推荐" prop="isRecommend">
                        <el-switch v-model="form.isRecommend" :disabled="billState"/>
                    </el-form-item>
                </el-col>
                <el-col :sm="24" :md="12" :xl="6">
                    <el-form-item label="文章摘要" prop="articleSummary">
                        <el-input type="textarea" v-model="form.articleSummary" :readonly="billState" placeholder="请输入文章摘要"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <editor-markdown 
        v-model="form.articleContent" 
        :height="430"
        v-if="!billState"></editor-markdown>
        <perview-markdown v-else :text="form.articleContent"></perview-markdown>
        <template #footer>
            <span>
                <el-button type="primary" v-if="!billState" :loading="submitLoading" @click="submitClick(ARTICLE_STATUS.DRAFT_STATE.value, submitLoading)">保存草稿</el-button>
                <el-button type="success" v-if="!billState" :loading="updateLoading" @click="submitClick(ARTICLE_STATUS.RELEASE_STATE.value, updateLoading)">完成</el-button>
                <el-button class="" @click="handleClose">关闭</el-button>
            </span>
        </template>
    </el-drawer>
</template>

<script setup>
import { reactive } from 'vue';
import { articleApi } from '@/api/article/article/article-api';
import { tagApi } from '@/api/article/tag/tag-api';
import { sortApi } from '@/api/article/sort/sort-api';
import { ElMessage } from 'element-plus';
import { ARTICLE_STATUS } from '@/constants/client/article';
import { montageStr } from '@/utils/tools-util';

// const DRAFT_STATE = ref(0);
// const RELEASE_STATE = ref(1);
// const WITHDRAW_STATE = ref(2);
// ========================= 实列挂载之前调用 =========================

onBeforeMount(() => {
    getInitList(tagApi, tagList);
    getInitList(sortApi, articleTypeList);
})

// ========================= 接收值 =========================
const articleProps = defineProps({
    listLength: {
        type: Number,
        default: 0
    }
})

// ========================= 弹框控制 =========================
let drawer = ref(false);
let dialogState = ref('add');
function onShowDrawer(type, row) {
    if(row) {
        for(let key in form) {
            form[key] = row[key];
        };
        form.id = row.id;
        form.tags = montageStr(row.tags, 'id');
    };
    dialogState.value = type;
    drawer.value = true;
};

// 组件向外暴露属性或方法
defineExpose({
    onShowDrawer,
    switchUpdate
});

// ========================= 计算属性 =========================
const typeTitle = computed(() => {
    if(dialogState.value == 'add') return '新增';
    if(dialogState.value == 'update') return '修改';
    if(dialogState.value == 'view') return '查看';
});

const billState = computed(() => {
    if(dialogState.value != 'view') return false;
    return true;
});

// ========================= 定义发射给父组件的方法 =========================
const emits = defineEmits(['updateArticleList']);

// ========================= 初始数据 =========================
// 文章标签数据
const tagList = ref([]);
const articleTypeList = ref([]);
async function getInitList(api, list) {
    try {
        let params = {
            state: true
        };
        const res = await api.list({params});
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
        list.value = res.data.data
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    };
};

// ========================= 表单 =========================
const form = reactive({
    id:'',                  // 主键
    tags:[],                // 文章标签
    articleSort:0,          // 文章排序
    articleAuthor:'',       // 文章作者
    sortName:'',            // 文章类别
    sortId:'',              // 文章类别id
    articleTitle:'',        // 文章标题
    articleSummary:'',      // 文章摘要
    articleContent:'',      // 文章内容
    articleCover:'',        // 文章封面
    status:null,            // 文章状态
    viewsCount:0,           // 文章浏览量
    commentsCount:0,        // 文章评论数
    like:0,                 // 文章点赞数
    isTop:false,            // 是否置顶
    isHot:false,            // 是否火热
    isRecommend:false,      // 是否推荐
    reprint:'',             // 转载地址
    editType:'md',          // 编辑类别
    createdAt:'',           // 创建时间
    updatedAt:'',           // 更新时间
});
// 表单校验
const rules = reactive({
    articleTitle:[
        { required: true, message: '请输入文章标题', trigger: 'blur' }
    ],
    articleSummary: [
        { required: true, message: '请输入文章摘要', trigger: 'blur' }
    ],
    articleAuthor: [
        { required: true, message: '请输入文章作者', trigger: 'blur' }
    ],
    tags: [
        { required: true, message: '请选择文章标签', trigger: 'blur' }
    ],
    sortId: [
        { required: true, message: '请选择文章类别', trigger: 'blur' }
    ],
});

// 文章类别选择
function sortChange(val) {
    articleTypeList.value.forEach(item => {
        if(item.id === val) {
            form.sortName = item.sortName;
            return
        };
    });
};

// 表单操作
const formRef = ref();
let submitLoading = ref(false);
let updateLoading = ref(false);
// 提交
function submitClick(status, loading) {
    formRef.value.validate(async (valid) => {
        console.log(loading)
        console.log(form.id)
        // return
        try {
            if(valid) {
                loading = true;
                let date = new Date();
                form.updatedAt = date;
                form.status = status;
                let res = null;
                if(form.id === '') {
                    // 第一次保存草稿为创建文章
                    delete form.id;
                    form.createdAt = date;
                    form.articleSort = parseInt(articleProps.listLength+1);
                    res = await articleApi.create(form);
                }else {
                    // 后续为更新
                    res = await articleApi.update(form);
                };
                !form.sortName && sortChange(form.sortId);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                !form.id ? ElMessage.success('新增成功') : ElMessage.success('修改成功');
                loading = false;
                drawer.value = false;
                emits('updateArticleList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        }finally {
            loading = false;
        };
    });
};

// 修改
function updateClick(status) {
    formRef.value.validate(async (valid) => {
        try {
            if(valid) {
                updateLoading.value = true;
                let date = new Date();
                form.updatedAt = date;
                form.status = status;
                let res = null;
                if(form.id === '') {
                    // 第一次保存草稿为创建文章
                    delete form.id;
                    form.createdAt = date;
                    form.articleSort = parseInt(articleProps.listLength+1);
                    res = await articleApi.create(form);
                }else {
                    // 后续为更新
                    res = await articleApi.update(form);
                };
                !form.sortName && sortChange(form.sortId);
                // const res = await articleApi.update(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                !form.id ? ElMessage.success('新增成功') : ElMessage.success('修改成功');
                updateLoading.value = false;
                drawer.value = false;
                emits('updateArticleList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            updateLoading.value = false;
        };
    });
};

// 修改推荐/置顶
async function switchUpdate(row) {
    try {
        if(row) {
            for(let key in form) {
                form[key] = row[key];
            };
            form.id = row.id;
            form.tags = montageStr(row.tags, 'id');
            const res = await articleApi.update(form);
            if(res.meta.status !== 200) throw new Error(res.meta.msg);
            ElMessage.success('修改成功');
            emits('updateArticleList');
            handleClose(row);
        };
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    }
};

// ========================= 文章关闭 =========================
function handleClose(row) {
    !row && formRef.value.resetFields(); // 重置表单
    for(let key in form) {
        form[key] = '';
    };
    form.id = '';
    form.articleSort = 1;
    form.sortId = '';
    form.status = null;
    form.viewsCount = 0;
    form.commentsCount = 0;
    form.like = 0;
    form.isTop = false;
    form.isHot = false;
    form.isTop = false;
    form.isRecommend = false;
    form.editType = 'md';
    drawer.value = false;
};
</script>

<style lang="scss" scoped>

</style>